package model

import (
	"errors"
	"ginBasic/app/common/lib"
	"ginBasic/global"
)

var AccessModel = new(Access)

type Access struct {
	Id          int    `form:"id" json:"id"`
	ModuleName  string `form:"module_name" json:"module_name"` //模块名称
	ActionName  string `form:"action_name" json:"action_name"` //操作名称
	Type        int    `form:"type" json:"type"`               //节点类型 :  1、表示模块    2、表示菜单     3、操作
	Url         string `form:"url" json:"url"`                 //路由跳转地址
	Icon        string `form:"icon" json:"icon"`               //图标
	ModuleId    int    `form:"module_id" json:"parentId"`      //此module_id和当前模型的id关联       module_id= 0 表示模块
	Sort        int    `form:"sort" json:"sort"`
	Description string `form:"description" json:"description"`
	Status      int    `form:"status" json:"status"`
	AddTime     int    `form:"add_time" json:"add_time"`
	UpdateTime  int    `form:"update_time" json:"update_time"`
	//Children    []Access `form:"children" json:"children" gorm:"foreignKey:ModuleId;references:Id"`
	Checked bool `gorm:"-"` // 忽略本字段
}

func (Access) TableName() string {
	return "access"
}

func (Access) List(where string) []Access {

	accessList := []Access{}
	//global.DB.Where(where).Preload("Children.Children").Find(&accessList)
	global.DB.Where(where).Order("sort ASC").Find(&accessList)
	return accessList

}

func (Access) Add(req *Access) (bool, error) {
	access := Access{
		ModuleName:  req.ModuleName,
		ActionName:  "",
		Type:        req.Type,
		ModuleId:    req.ModuleId,
		Url:         req.Url,
		Icon:        req.Icon,
		Sort:        req.Sort,
		Status:      req.Status,
		Description: req.Description,
		AddTime:     int(lib.GetUnix()),
		UpdateTime:  int(lib.GetUnix()),
	}
	err := global.DB.Create(&access).Error
	if err != nil {
		return false, err
	}
	return true, nil
}

// 根据id返回用户信息
func (Access) GetInfoById(id int) Access {
	var access Access
	global.DB.Where("id=?", id).Find(&access)
	return access
}

func (Access) Edit(req *Access) (bool, error) {
	access := Access{Id: req.Id}
	global.DB.Find(&access)
	access.ActionName = req.ActionName
	access.Url = req.Url
	access.Icon = req.Icon
	access.Type = req.Type
	access.Status = req.Status
	access.ModuleId = req.ModuleId
	access.Sort = req.Sort
	access.Description = req.Description
	access.UpdateTime = int(lib.GetUnix())
	err := global.DB.Save(&access).Error
	if err != nil {
		return false, err
	}
	return true, nil
}

func (Access) Delete(id int) (bool, error) {
	var cnt int64
	global.DB.Model(&Access{}).Select("count(1)").Where("module_id=?", id).Find(&cnt)
	if cnt > 0 {
		return false, errors.New("该菜单下面存在子菜单，请删除后再操作！")
	}
	err := global.DB.Delete(&Access{}, id).Error
	if err != nil {
		//记录删除报错的原因 TODO
		return false, err
	}
	return true, nil
}
